########################################
###      Yankelovich 2024 Bovitz     ###
###            Run Earned V Paid     ###
###            Mac Lockhart          ###
### Run after clean_EarnedVPaid.R    ###
###        Created: 10/25/2024       ###
###        Updated: 10/25/2024       ###
########################################

library(readr)
library(tidyverse)
library(dplyr)
library(kableExtra)
library(stargazer)
library(data.table)
library(purrr)      # map_df()
library(broom)      # tidy()
library(ggplot2)

# Header -----------------------------------------------------------------------

if(Sys.info()[7] == "laura"){
  setwd("/Users/laura/Dropbox/RA/MIT Evolving Election Administration Landscape/Earned vs Paid Media/")
}
if(Sys.info()[7]=="ml2999"){
  setwd("E:/Dropbox/School/RA Work/'22 Seth & Thad/MIT Evolving Election Administration Landscape/Earned vs Paid Media/")
}
if(Sys.info()[7]=="maclockhart"){
  setwd("/users/maclockhart/Dropbox/School/RA Work/'22 Seth & Thad/MIT Evolving Election Administration Landscape/Earned vs Paid Media/")
}

DF <- fread("2_data/wave1_clean.csv")
DF$treatment <- factor(DF$treatment, levels = c("Control", "Earned Media", "Paid Media"))


########################
#Main analyses
#######################

########################
#Within wave analysis
#######################
maricopa <- lm(maricopapost ~ treatment, DF)
state <- lm(statepost  ~ treatment, DF)
country <- lm(countrypost  ~ treatment, DF)
pollworker <- lm(pollworkerpost  ~ treatment, DF)
votelikely <- lm(votelikelypost  ~ treatment, DF)

stargazer(maricopa, state, country,
          pollworker, votelikely,
          type = "html",
          out = "5_tables/EVP_MainTable.html",
          title = "Effect of EAC and Trump messages on trust and behavior outcomes.",
          column.labels = c("Maricopa (1-4)", 
                            "State Vote (1-4)", "National Vote (1-4)",
                            "Poll Worker (1/0)", "Vote Likelihood (1-5)"),
          #dep.var.labels = c("Trust Measures"),
          dep.var.labels.include = F,
          covariate.labels = c("Earned Media", "Paid Media" ,"Constant"),
          omit.stat = c("f","adj.rsq", "ser"))


########################
#Binary within wave analysis
#######################
maricopa <- lm(d_maricopa ~ treatment, DF)
state <- lm(d_state  ~ treatment, DF)
country <- lm(d_country  ~ treatment, DF)
pollworker <- lm(d_pollworker  ~ treatment, DF)
votelikely <- lm(d_votelikely  ~ treatment, DF)

stargazer(maricopa, state, country,
          pollworker, votelikely,
          type = "html",
          out = "5_tables/EVP_BinaryTable.html",
          title = "Effect of EAC and Trump messages on binary measures of trust and behavior outcomes.",
          column.labels = c("Maricopa (1-4)", 
                            "State Vote (1-4)", "National Vote (1-4)",
                            "Poll Worker (1/0)", "Vote Likelihood (1-5)"),
          #dep.var.labels = c("Trust Measures"),
          dep.var.labels.include = F,
          covariate.labels = c("Earned Media", "Paid Media" ,"Constant"),
          omit.stat = c("f","adj.rsq", "ser"))

########################
#Change in Outcomes analysis
#######################
maricopa <- lm(maricopachange ~ treatment, DF)
state <- lm(statechange  ~ treatment, DF)
country <- lm(countrychange  ~ treatment, DF)
pollworker <- lm(pollworkerchange  ~ treatment, DF)
votelikely <- lm(votelikelychange  ~ treatment, DF)

stargazer(maricopa, state, country,
          pollworker, votelikely,
          type = "html",
          out = "5_tables/EVP_ChangeTable.html",
          title = "Effect of Earned and Paid messages on change in measures of trust and behavior outcomes. Main outcome (Maricopa) not measured pre-treatment.",
          column.labels = c("Maricopa (1-4)", 
                            "State Vote (1-4)", "National Vote (1-4)",
                            "Poll Worker (1/0)", "Vote Likelihood (1-5)"),
          #dep.var.labels = c("Trust Measures"),
          dep.var.labels.include = F,
          covariate.labels = c("Earned Media", "Paid Media" ,"Constant"),
          omit.stat = c("f","adj.rsq", "ser"))



########################
#Change by Party Analysis
#######################
DF$party <- case_when(DF$party_short=="Democrat" ~ "DEM",
                      DF$party_short=="Republican" ~ "REP",
                      .default="IND")
DF$party <- factor(DF$party, levels=c("IND", "DEM", "REP"))

maricopa <- lm(maricopachange ~ treatment*party, DF)
state <- lm(statechange  ~ treatment*party, DF)
country <- lm(countrychange  ~ treatment*party, DF)
pollworker <- lm(pollworkerchange  ~ treatment*party, DF)
votelikely <- lm(votelikelychange  ~ treatment*party, DF)

stargazer(maricopa, state, country,
          pollworker, votelikely,
          type = "html",
          out = "5_tables/EVP_ChangeTableByParty.html",
          title = "Effect of Earned and Paid messages on change in measures of trust and behavior outcomes. Main outcome (Maricopa) not measured pre-treatment.",
          column.labels = c("Maricopa (1-4)", 
                            "State Vote (1-4)", "National Vote (1-4)",
                            "Poll Worker (1/0)", "Vote Likelihood (1-5)"),
          #dep.var.labels = c("Trust Measures"),
          dep.var.labels.include = F,
          covariate.labels = c("Earned Media", "Paid Media" ,
                               "Democrat", "Republican",
                               "Democrat X Earned", "Democrat X Paid",
                               "Republican X Earned", "Republican X Paid",
                               "Constant"),
          omit.stat = c("f","adj.rsq", "ser"))




# ------------------------------------------------------------------
# Coefficient plot for paper
# ------------------------------------------------------------------
maricopa <- lm(maricopachange ~ treatment, DF)
state <- lm(statechange  ~ treatment, DF)
country <- lm(countrychange  ~ treatment, DF)
pollworker <- lm(pollworkerchange  ~ treatment, DF)
votelikely <- lm(votelikelychange  ~ treatment, DF)

# Named vector maps outcome variables to nice y-axis labels
outcomes <- c(
  maricopachange  = "Maricopa\nTrust (1–4)",
  statechange     = "State-Level\nTrust (1–4)",
  countrychange   = "National\nTrust (1–4)",
  pollworkerchange= "Poll-worker\nConfidence (0-1)",
  votelikelychange= "Vote\nLikelihood (1–5)"
)

coef_df <- map_df(names(outcomes), function(v) {
  
  mod <- lm(reformulate("treatment", v), data = DF)
  
  broom::tidy(mod, conf.int = TRUE) %>% 
    filter(term != "(Intercept)") %>%          # drop intercept
    mutate(
      term = recode(term,
                    "treatmentEarned Media"       = "Earned Media",
                    "treatmentPaid Media"  = "Paid Media"),
      term = factor(term,
                    levels = c("Earned Media", "Paid Media")),
      outcome = outcomes[[v]]
    )
})


evp_plot <- ggplot(coef_df,
                   aes(x = estimate,
                       y = outcome,
                       group=term,
                       color = term)) +
  geom_vline(xintercept = 0,
             colour = "grey50") +
  geom_errorbarh(aes(xmin = conf.low, xmax = conf.high),
                 height   = 0,
                 size     = 1,
                 position = position_dodge(width = .6)) +
  geom_point(size = 3,
             position = position_dodge(width = 0.6)) +
  scale_color_manual(values = c("grey10", "grey50", "grey90")) +
  #scale_shape_manual(values  = c(16, 17, 15)) +
  labs(
    title    = "Effect of Earned and Paid Media Messages",
    subtitle = "Positive values indicate an increase from baseline (post–pre)\nor, for Maricopa,a higher post-treatment score",
    x        = "Coefficient Estimate (change score)",
    y        = "",
    color = "Treatment") +
  theme_minimal(base_size = 14) +
  theme(legend.position = "bottom")

ggsave("4_figures/EVP_ChangePlot.png",
       plot   = evp_plot,
       width  = 7,
       height = 6,
       dpi    = 500)


# ------------------------------------------------------------------
# Coefficient plot for paper - no pretreatment
# ------------------------------------------------------------------
maricopa <- lm(maricopapost ~ treatment, DF)
state <- lm(statepost  ~ treatment, DF)
country <- lm(countrypost  ~ treatment, DF)
pollworker <- lm(pollworkerpost  ~ treatment, DF)
votelikely <- lm(votelikelypost  ~ treatment, DF)

# Named vector maps outcome variables to nice y-axis labels
outcomes <- c(
  maricopapost  = "Maricopa\nTrust (1–4)",
  statepost     = "State-Level\nTrust (1–4)",
  countrypost   = "National\nTrust (1–4)",
  pollworkerpost= "Poll-worker\nConfidence (0-1)",
  votelikelypost= "Vote\nLikelihood (1–5)"
)

coef_df <- map_df(names(outcomes), function(v) {
  
  mod <- lm(reformulate("treatment", v), data = DF)
  
  broom::tidy(mod, conf.int = TRUE) %>% 
    filter(term != "(Intercept)") %>%          # drop intercept
    mutate(
      term = recode(term,
                    "treatmentEarned Media"       = "Earned Media",
                    "treatmentPaid Media"  = "Paid Media"),
      term = factor(term,
                    levels = c("Earned Media", "Paid Media")),
      outcome = outcomes[[v]]
    )
})


evp_plot <- ggplot(coef_df,
                   aes(x = estimate,
                       y = outcome,
                       group=term,
                       color = term)) +
  geom_vline(xintercept = 0,
             colour = "grey50") +
  geom_errorbarh(aes(xmin = conf.low, xmax = conf.high),
                 height   = 0,
                 size     = 1,
                 position = position_dodge(width = .6)) +
  geom_point(size = 3,
             position = position_dodge(width = 0.6)) +
  scale_color_manual(values = c("grey10", "grey50", "grey90")) +
  #scale_shape_manual(values  = c(16, 17, 15)) +
  labs(
    title    = "Effect of Earned and Paid Media Messages",
    subtitle = "Positive values indicate a higher post-treatment score",
    x        = "Coefficient Estimate (Difference in Means)",
    y        = "",
    color = "Treatment") +
  theme_minimal(base_size = 14) +
  theme(legend.position = "bottom")

ggsave("4_figures/EVP_NoChangePlot.png",
       plot   = evp_plot,
       width  = 7,
       height = 6,
       dpi    = 500)
